import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Select, Input, Button, Table, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { reqProducts, AxiosResponse, reqSearchProducts, reqUpdateProductStatus, Sold } from '../../../api';
import { PAGE_NUM, PAGE_SIZE } from '../../../utils/constants';

enum Status {
    Success,
    Fail
}
type Product = {
    status: number;
    imgs: string[];
    _id: string;
    name: string;
    desc: string;
    price: number;
    pCategoryId: string;
    categoryId: string;
    detail: string;
    __v: number;
};
type ProductConfig = {
    pageNum: number;
    total: number;
    pages: number;
    pageSize: number;
    list: Product[];
};
type DataInfo = {
    status: Status.Success;
    data: ProductConfig;
} | {
    status: Status.Fail;
    msg: string;
};

enum SearchSelect {
    Name = '0',
    Description = '1'
}
type SelectValueType = SearchSelect.Name | SearchSelect.Description;

type Columns = {
    title: string;
    dataIndex?: string;
    render?: (product: Product) => React.ReactNode;
    width?: number;
};

const { Option } = Select;

// Product 默认子路由组件
const ProductHome: React.FC = () => {
    const [isLoading, setLoading] = useState<boolean>(false);
    const [{ total, list }, setProducts] = useState<Pick<ProductConfig, 'total' | 'list'>>({ total: 0, list: [] });
    const [searchType, setSearchType] = useState<SelectValueType>(SearchSelect.Name);
    const [fieldValue, setFieldValue] = useState<string>('');
    const navigate = useNavigate();
    const pageNumRef = useRef<number>(PAGE_NUM);
    const getAsyncProducts = async (pageNum: number): Promise<void> => {
        pageNumRef.current = pageNum; // 保存pageNum（当前页码） 让其他方法可以看到
        setLoading(true);
        const { data }: AxiosResponse<DataInfo> = await reqProducts(pageNum, PAGE_SIZE);
        setLoading(false);
        if (data.status === Status.Success) {
            const { total, list }: ProductConfig = data.data;
            setProducts({
                total, list
            });
        }
    };
    const getAsyncSearchProducts = async (pageNum: number): Promise<void> => {
        pageNumRef.current = pageNum; // 保存pageNum（当前页码） 让其他方法可以看到
        setLoading(true);
        const { data }: AxiosResponse<DataInfo> = await reqSearchProducts({ pageNum, pageSize: PAGE_SIZE, searchName: fieldValue }, searchType === SearchSelect.Description);
        setLoading(false);
        if (data.status === Status.Success) {
            const { total, list }: ProductConfig = data.data;
            setProducts({
                total, list
            });
        }
    };
    const onChange = (value: SelectValueType): void => {
        setSearchType(value);
    };
    const onInputChange = ({ target }: React.ChangeEvent<HTMLInputElement>): void => {
        setFieldValue(target.value);
    };
    const onSubmitSearch = (): void => {
        getAsyncSearchProducts(PAGE_NUM);
    };
    const title: React.ReactNode = (
        <span>
            <Select value={searchType} style={{ width: 150 }} onChange={onChange}>
                <Option value="0">按名称搜索</Option>
                <Option value="1">按描述搜索</Option>
            </Select>
            <Input placeholder="关键字" onChange={onInputChange} style={{ margin: '0 15px', width: 150 }} value={fieldValue} />
            <Button type="primary" onClick={onSubmitSearch}>搜索</Button>
        </span>
    );
    const extra: React.ReactNode = (
        <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('addupdate')}>添加商品</Button>
    );
    const columns: Columns[] = [
        {
            title: '商品名称',
            dataIndex: 'name',
        },
        {
            title: '商品描述',
            dataIndex: 'desc',
        },
        {
            title: '价格',
            dataIndex: 'price',
            render: price => `￥${price}`
        },
        {
            width: 100,
            title: '状态',
            render({ status, _id }) {
                const handleAsyncUpdate = async () => {
                    const sold: Sold = status === Sold.Yes ? Sold.No : Sold.Yes;
                    const { data }: AxiosResponse<DataInfo> = await reqUpdateProductStatus(_id, sold);
                    if (data.status === Status.Success) {
                        message.success('更新商品成功');
                        getAsyncProducts(pageNumRef.current);
                    }
                };
                return (
                    <span>
                        <Button
                            type="primary"
                            onClick={handleAsyncUpdate}
                        >
                            {status === Sold.No ? '上架' : '下架'}
                        </Button>
                        <span>{status === Sold.Yes ? '在售' : '已下架'}</span>
                    </span>
                );
            }
        },
        {
            title: '操作',
            render(product) {
                return (
                    <span>
                        <Button type="link" onClick={() => navigate('detail', { state: product })}>详情</Button>
                        <Button type="link" onClick={() => navigate('addupdate', { state: product })}>修改</Button>
                    </span>
                );
            },
            width: 100
        }
    ];
    useEffect(() => {
        getAsyncProducts(PAGE_NUM);
    }, []);
    return (
        <Card title={title} extra={extra}>
            <Table rowKey="_id" bordered loading={isLoading} pagination={{
                showQuickJumper: true,
                current: pageNumRef.current,
                total,
                defaultPageSize: PAGE_SIZE,
                onChange: fieldValue.trim() === '' ? getAsyncProducts : getAsyncSearchProducts
            }} dataSource={list} columns={columns} />
        </Card>
    );
};

export default ProductHome;